/* Bazinga - MPD Jukebox
 * Copyright (C) 2010 m3Soft (Martin Sieke, Matthias Sieke, Matthias Bockstegers)
 * 
 * This program is distributed under the terms of the GNU General Public License.
 * You can redistribute  and/or modify it under the terms of the GNU General Public License 
 * as published by the Free Software Foundation, either version 3 of the License, 
 * or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; 
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
 * See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along with this program.  
 * If not, see http://www.gnu.org/licenses
 */

package de.m3soft.bazinga;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.bff.javampd.MPD;
import org.bff.javampd.MPDDatabase;
import org.bff.javampd.MPDPlayer;
import org.bff.javampd.MPDPlaylist;
import org.bff.javampd.exception.MPDConnectionException;
import org.bff.javampd.exception.MPDDatabaseException;
import org.bff.javampd.exception.MPDException;
import org.bff.javampd.exception.MPDPlayerException;
import org.bff.javampd.exception.MPDPlaylistException;
import org.bff.javampd.exception.MPDResponseException;
import org.bff.javampd.objects.MPDAlbum;
import org.bff.javampd.objects.MPDArtist;
import org.bff.javampd.objects.MPDSong;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class Methoden {
	private MPD mpd;

	private ArrayList<String[]> youtubeSongs;

	private BazingaGUI myGUI;

	private SortedProperties properties;

	Methoden(MPD mpd, BazingaGUI myGUI, SortedProperties properties) {
		this.mpd = mpd;
		this.myGUI = myGUI;
		this.properties = properties;
		youtubeSongs = new ArrayList<String[]>();
	}

	public MPD getMPD() {
		return mpd;
	}

	// returns the current playlist
	public List<MPDSong> getSongList() {
		try {
			return mpd.getMPDPlaylist().getSongList();
		} catch (MPDPlaylistException | MPDConnectionException e) {
			System.out.println("Error fetching Playlist: \n" + e);
		}
		return null;

	}

	public MPDDatabase getDatabase() {
		return mpd.getMPDDatabase();
	}

	// returns the MPDPlaylist
	public MPDPlaylist getPlayList() {
		return mpd.getMPDPlaylist();
	}

	public MPDPlayer getPlayer() {
		return mpd.getMPDPlayer();
	}

	// returns length of current playlist (queue)
	public int getPlaylistLength() {
		return getSongList().size();
	}

	// returns a random number between 1 and {max}
	public int getRandom(int max) {
		int rand = (int) (Math.random() * max) + 1;
		return rand;
	}

	public MPDArtist getArtist(MPDSong mpdSong) {
		MPDArtist mpdArtist;
		try {
			mpdArtist = mpdSong.getArtist();
			mpdSong.getArtist().getName();
		} catch (Exception e) {
			if (mpdSong.getFile().toLowerCase().contains("http://")) {
				mpdArtist = new MPDArtist("Youtube");
				mpdArtist.setName("Youtube");
			} else {
				mpdArtist = new MPDArtist("unknown");
				mpdArtist.setName("unknown");
			}
			mpdSong.setArtist(mpdArtist);
		}
		return mpdArtist;
	}

	public String getTitle(MPDSong mpdSong) {
		String mpdTitle;
		try {
			mpdTitle = mpdSong.getTitle();
		} catch (Exception e) {
			mpdTitle = "Unknown Title";
			mpdSong.setTitle(mpdTitle);
		}
		if (mpdTitle == "" || mpdTitle == null) {
			if (mpdSong.getFile().toLowerCase().contains("http://")) {
				mpdTitle = "Unknown Title";
			} else {
				mpdTitle = mpdSong.getFile();
			}

		}

		return mpdTitle;
	}

	public MPDAlbum getAlbum(MPDSong mpdSong) {
		MPDAlbum mpdAlbum;
		try {
			mpdAlbum = mpdSong.getAlbum();
			mpdAlbum.getName();
		} catch (Exception e) {
			if (mpdSong.getFile().toLowerCase().contains("http://")) {
				mpdAlbum = new MPDAlbum("Youtube");
				mpdAlbum.setName("Youtube");
			} else {
				mpdAlbum = new MPDAlbum("unknown");
				mpdAlbum.setName("unknown");
			}
			mpdSong.setAlbum(mpdAlbum);
		}
		return mpdAlbum;
	}

	// adds one random song to playlist (queue)
	public void addRandomSong() {
		addRandomSong(1);
	}

	// adds {number} songs to playlist (queue)
	public void addRandomSong(int number) {
		List<String> allSongFiles;
		try {
			if (getDatabase().listAllSongs().isEmpty())
				return;
			allSongFiles = new ArrayList<String>(getDatabase().listAllSongFiles());
		} catch (MPDDatabaseException e) {
			System.out.println("MPDDatabaseException while trying to list all song files.");
			return;
		} catch (MPDConnectionException e) {
			System.out.println("MPDConnectionException while trying to list all song files.");
			return;
		}
		String song;
		List<MPDSong> musicList;
		MPDSong mpdSong;

		for (int i = 0; i < number; i++) {
			song = allSongFiles.get(getRandom(allSongFiles.size()));
			// System.out.println(song);
			try {
				musicList = new ArrayList<MPDSong>(getDatabase().searchFileName(song));
			} catch (MPDDatabaseException e) {
				System.out.println("MPDDatabaseException while searching random song.");
				return;
			} catch (MPDConnectionException e) {
				System.out.println("MPDConnectionException while searching random song.");
				return;
			}
			mpdSong = (MPDSong) musicList.get(0);
			addSong(mpdSong);
			myGUI.setConsole("Added \"" + song + "\"");
		}
	}

	// adds a defined song to playlist (queue)
	public String addSong(MPDSong mpdSong) {
		int mtb = 3, mta = 2, i = 0, j = 0, mt = 20;

		if (mpdSong.getFile() == null || getTitle(mpdSong) == null || getAlbum(mpdSong) == null || getArtist(mpdSong) == null)
			return "Song has incomplete metadata.";

		// System.out.println(mpdSong.getFile() + " | " + mpdSong.getArtist() + " | " + mpdSong.getTitle() + " | " + mpdSong.getAlbum());

		// get needed properties
		try {
			mta = Integer.parseInt(properties.getProperty("maxTracksPerArtist")) + 0;
		} catch (NumberFormatException e) {
			return "Error reading maxTracksPerArtist. Check file bazinga.cfg";
		}

		try {
			mtb = Integer.parseInt(properties.getProperty("maxTracksPerAlbum")) + 0;
		} catch (NumberFormatException e) {
			return "Error reading maxTracksPerAlbum. Check file bazinga.cfg";
		}

		try {
			mt = Integer.parseInt(properties.getProperty("maxTracks")) + 0;
		} catch (NumberFormatException e) {
			return "Error reading maxTracks. Check file bazinga.cfg";
		}

		// if playlist allready too big
		if (getPlaylistLength() >= mt) {
			return "sorry, playlist allready too big...";
		}
		// TODO: find solution for adding songs
		// if song allready in playlist
		if (getSongList().contains(mpdSong)/*
											 * && !song.getAlbum().getName().
											 * toLowerCase().contains("youtube")
											 */) {
			return "Song allready present in playlist...";
		}

		// run through playlist and find accurences of artist and album
		for (MPDSong song : getSongList()) {
			if (getArtist(song).getName().contains(getArtist(mpdSong).getName()))
				i++;
			if (getAlbum(song).getName().contains(getAlbum(mpdSong).getName()))
				j++;
			if (i >= mta/*
						 * &&
						 * !song.getArtist().getName().toLowerCase().contains(
						 * "youtube")
						 */) {
				return "Please no more than " + mta + " songs of an artist!";
			}
			if (j >= mtb/*
						 * && !song.getAlbum().getName().toLowerCase().contains(
						 * "youtube")
						 */) {
				return "Please no more than " + mtb + " songs of an album!";
			}
		}

		// if everything is fine, add song
		try {
			getPlayList().addSong(mpdSong);
		} catch (MPDPlaylistException e) {
			System.out.println("MPDPlaylistException while trying to add song.");
			return "MPDPlaylistException while trying to add song.";
		} catch (MPDConnectionException e) {
			System.out.println("MPDConnectionException while trying to add song.");
			return "MPDConnectionException while trying to add song.";
		}
		if (mpdSong.getFile().toLowerCase().contains("http://")) {
			String[] ytsong = { mpdSong.getFile(), mpdSong.getTitle() };
			youtubeSongs.add(ytsong);
		}

		return "Added \"" + getTitle(mpdSong) + " (" + getArtist(mpdSong) + ") " + "\"";
	}

	// returns a list of all added youtube songs TODO bitte diese aussage
	// überprüfen
	public ArrayList<String[]> getYoutubeSongs() {
		return youtubeSongs;
	}

	// search a song on database and return a list of results
	public List<MPDSong> findSong(String s) {
		if (s.equals("elton john")) {

			MPDSong bazingaSong = new MPDSong();

			bazingaSong.setFile("http://bootlog.dyndns.org/bazinga.mp3");
			bazingaSong.setArtist(new MPDArtist("Youtube"));
			bazingaSong.setAlbum(new MPDAlbum("Youtube"));
			bazingaSong.setTitle("Bazinga!");

			addSong(bazingaSong);

			String[] aSong = { bazingaSong.getFile(), bazingaSong.getTitle() };
			youtubeSongs.add(aSong);

			// return null;

			// return youtubeSearch("bazinga (all of them)");
		}

		ArrayList<MPDSong> tempList, musicList;
		int n = 0;
		int spaces[];
		String strings[];
		s = s.replaceAll("[^A-Za-z0-9+-äÄöÖüÜß' ]", "").replaceAll("\\.", "");

		// in case the search string is empty
		if (s == null || s.isEmpty() || s == "" || s.equals("") || s.equals(" ")) {
			tempList = new ArrayList<MPDSong>();
			try {
				tempList.addAll(getDatabase().listAllSongs());
			} catch (MPDDatabaseException e) {
				System.out.println("MPDDatabaseException while trying to list all songs.");
				return new ArrayList<MPDSong>();
			} catch (MPDConnectionException e) {
				System.out.println("MPDConnectionException while trying to list all songs.");
				return new ArrayList<MPDSong>();
			}
			musicList = new ArrayList<MPDSong>();

			for (MPDSong song : tempList) {
				if (song.getArtist() != null && song.getAlbum() != null && song.getTitle() != null)
					musicList.add(song);
			}

			return musicList;
		}

		// in case there are multiple terms in search string
		if (s.contains(" ")) {

			// count spaces
			for (int i = 0; i < s.length(); i++) {
				if (s.charAt(i) == ' ')
					n++;
			}

			spaces = new int[n + 2];
			spaces[0] = -1; // necessary offset for first term
			spaces[n + 1] = s.length(); // end of string
			strings = new String[n + 1]; // array of search terms
			n = 1; // n=0 allready in use

			// find spaces and add position to int array spaces
			for (int i = 0; i < s.length(); i++) {
				if (s.charAt(i) == ' ') {
					spaces[n] = i;
					n++;
				}
			}

			// find substrings and add to String array strings
			for (int i = 0; i < strings.length; i++) {
				strings[i] = s.substring(spaces[i] + 1, spaces[i + 1]);
			}
		} else { // in case the search string contains only one term
			strings = new String[1];
			strings[0] = s; // add search string to array
		}

		tempList = new ArrayList<MPDSong>();
		musicList = new ArrayList<MPDSong>();

		// add all search results (also duplicates) to one big temporary list
		for (int i = 0; i < strings.length; i++) {
			try {
				tempList.addAll(getDatabase().searchFileName(strings[i]));
				tempList.addAll(getDatabase().searchAlbum(new MPDAlbum(strings[i])));
				tempList.addAll(getDatabase().searchArtist(new MPDArtist(strings[i])));
				tempList.addAll(getDatabase().searchTitle(strings[i]));
			} catch (MPDDatabaseException e) {
				System.out.println("MPDDatabaseException while trying to search songs.");
				return new ArrayList<MPDSong>();
			} catch (MPDConnectionException e) {
				System.out.println("MPDConnectionException while trying to search songs.");
				return new ArrayList<MPDSong>();
			}
		}

		// run through temp list, perform 'AND' search and remove duplicates
		for (MPDSong song : tempList) {
			n = 0;
			for (int i = 0; i < strings.length; i++) {
				if (song.getArtist() != null && song.getArtist().getName().toLowerCase().contains(strings[i].toLowerCase()))
					n++;
				else if (song.getAlbum() != null && song.getAlbum().getName().toLowerCase().contains(strings[i].toLowerCase()))
					n++;
				else if (song.getTitle() != null && song.getTitle().toLowerCase().contains(strings[i].toLowerCase()))
					n++;
				else if (song.getFile() != null && song.getFile().toLowerCase().contains(strings[i].toLowerCase()))
					n++;
			}
			if (n >= strings.length && song.getFile() != null && song.getTitle() != null && song.getAlbum() != null && song.getArtist() != null && !musicList.contains(song))
				musicList.add(song);
		}
		return musicList;
	}

	// remove already played songs - the current playing song is always the
	// first in queue
	public void removePlayed() {
		if (properties.getProperty("master").equalsIgnoreCase("true")) {
			try {
				MPDSong currentPlaying;
				currentPlaying = mpd.getMPDPlaylist().getCurrentSong();

				List<MPDSong> songList = mpd.getMPDPlaylist().getSongList();

				if (songList.get(0) != null && !songList.get(0).equals(currentPlaying)) {
					getPlayList().removeSong(songList.get(0));
				}

			} catch (MPDPlaylistException e) {
				System.out.println("MPDPlaylistException while trying to remove played songs.");
				return;
			} catch (MPDConnectionException e) {
				System.out.println("MPDConnectionException while trying to remove played songs.");
				return;
			}
		}
	}

	public void play() {
		try {
			if (getPlayer().getStatus().equals(MPDPlayer.PlayerStatus.STATUS_PLAYING))
				getPlayer().pause();
			else {
				if (getPlaylistLength() == 0) {
					addRandomSong();
				}
				getPlayer().play();
			}
		} catch (MPDPlayerException e) {
			System.out.println("MPDPlayerException while performing \"play\".");
			return;
		} catch (MPDConnectionException e) {
			System.out.println("MPDConnectionException while performing \"play\".");
			return;
		} catch (MPDException e) {
			System.out.println("MPDException while performing \"play\".");
			return;
		}
	}

	// play next track
	public void playNext() {
		if (getPlaylistLength() <= 1) {
			addRandomSong();
		}
		try {
			if (getPlayer().getStatus().equals(MPDPlayer.PlayerStatus.STATUS_PLAYING))
				getPlayer().playNext();
			else {
				getPlayer().play();
				getPlayer().playNext();
			}

		} catch (MPDPlayerException e) {
			System.out.println("MPDPlayerException while performing \"skip\".");
			return;
		} catch (MPDConnectionException e) {
			System.out.println("MPDConnectionException while performing \"skip\".");
			return;
		} catch (MPDException e) {
			System.out.println("MPDException while performing \"skip\".");
			return;
		}
	}

	// stop playing
	public void stopPlaying() {
		try {
			if (!getPlayer().getStatus().equals(MPDPlayer.PlayerStatus.STATUS_STOPPED)) {
				getPlayer().stop();
			}
		} catch (MPDPlayerException e) {
			System.out.println("MPDPlayerException while performing \"stop\".");
			return;
		} catch (MPDConnectionException e) {
			System.out.println("MPDConnectionException while performing \"stop\".");
			return;
		} catch (MPDException e) {
			System.out.println("MPDException while performing \"stop\".");
			return;
		}
	}

	public void removeSong(int i) {
		if (i >= getSongList().size() || getSongList().get(i) == null)
			return;
		try {
			if (getPlayList().getCurrentSong().equals(getSongList().get(i)) && getPlayer().getStatus().equals(MPDPlayer.PlayerStatus.STATUS_PLAYING))
				playNext();
			else
				mpd.getMPDPlaylist().removeSong(getSongList().get(i));
		} catch (MPDPlaylistException e) {
			System.out.println("MPDPlaylistException while trying to remove song.");
			return;
		} catch (MPDConnectionException e) {
			System.out.println("MPDConnectionException while trying to remove song.");
			return;
		} catch (MPDException e) {
			System.out.println("MPDException while trying to remove song.");
			return;
		}
	}

	// write config to file
	public void saveConfig() {
		FileOutputStream outstream;
		try {
			outstream = new FileOutputStream("bazinga.cfg");
			properties.store(outstream, null);
			outstream.close();
		} catch (FileNotFoundException e) {
			System.out.println("FileNotFoundException while trying to save config.");
			return;
		} catch (IOException e) {
			System.out.println("IOException while trying to save config.");
			return;
		}
	}

	// set a property
	public void setProperty(String key, String value) {
		properties.setProperty(key, value);
	}

	// set value of a property
	public String getProperty(String key) {
		return properties.getProperty(key);
	}

	// skip to next track and fade out (for over sized songs)
	public void skip() {
		int volume = 0;
		try {
			volume = getPlayer().getVolume();
		} catch (MPDResponseException e) {
			System.out.println("Exception while trying to fade out an over sized song. Maybe there is no software mixer defined in mpd");
		} catch (MPDConnectionException e) {
			System.out.println("Exception while trying to fade out an over sized song. Maybe there is no software mixer defined in mpd");
		}

		for (int i = volume; i >= 0; i -= 3) {
			try {
				getPlayer().setVolume(i);
			} catch (MPDResponseException e) {
				System.out.println("Exception while trying to fade out an over sized song. Maybe there is no software mixer defined in mpd");
			} catch (MPDConnectionException e) {
				System.out.println("Exception while trying to fade out an over sized song. Maybe there is no software mixer defined in mpd");
			}
			try {
				Thread.sleep(200);
			} catch (InterruptedException e) {
				System.out.println("Exception while trying sleep 200 ms.");
			}
		}

		try {
			getPlayer().playNext();
		} catch (MPDPlayerException e1) {
			System.out.println("Exception while trying to fade out an over sized song. Maybe there is no software mixer defined in mpd");
		} catch (MPDConnectionException e1) {
			System.out.println("Exception while trying to fade out an over sized song. Maybe there is no software mixer defined in mpd");
		}
		try {
			Thread.sleep(50);
		} catch (InterruptedException e1) {
			System.out.println("Exception while trying sleep 200 ms.");
		}
		try {
			getPlayer().setVolume(volume);
		} catch (MPDPlayerException e1) {
			System.out.println("Exception while trying to fade out an over sized song. Maybe there is no software mixer defined in mpd");
		} catch (MPDConnectionException e1) {
			System.out.println("Exception while trying to fade out an over sized song. Maybe there is no software mixer defined in mpd");
		}
	}

	// download an album art and return file path
	public String getAlbumArt(String artist, String album) {
		if (artist.equalsIgnoreCase("youtube")) {
			return "img/yt.png";
		}

		File file = new File("albumArt/" + artist + " - " + album + ".jpg");
		if (file.exists()) {
			return "albumArt/" + artist + " - " + album + ".jpg";
		}

		URLConnection connnection = null;
		InputStream inputStream = null;
		OutputStream outputStream = null;
		byte[] dataPart = new byte[1024];
		int data;
		String filename = "albumArt.xml";
		String apiKey = "67f269e6f45ee02f2c01f74aa7f81283";
		String imageSize = "large";

		artist = artist.replaceAll("[^A-Za-z0-9äöüÄÜÖ+-<> ]", "").replaceAll("/", "");
		album = album.replaceAll("[^A-Za-z0-9äöüÄÜÖ+-<> ]", "").replaceAll("/", "");

		URL queryurl = null;
		try {
			queryurl = new URL(("http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=" + apiKey + "&artist=" + artist + "&album=" + album).replace(" ", "%20"));
		} catch (MalformedURLException e) {
			System.out.println("Problem on getting Album Art, query-url was not well-formed");
			// myGUI.notification("Error", "Problem on getting Album Art, query-url was not well-formed", "warning");
			return "img/icon.png";
		}

		try {
			connnection = queryurl.openConnection();
			connnection.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; U; Linux i686; de; rv:1.9.2.3) Gecko/20100423 Ubuntu/10.04 (lucid) Firefox/3.6.3");

		} catch (IOException e) {
			System.out.println("Problem on getting album art, can't connect to audioscrobbler image search");
			// myGUI.notification("Error", "Problem on getting Album Art, can't connect to images.google.com", "warning");
			return "img/icon.png";
		}
		try {
			inputStream = new BufferedInputStream(connnection.getInputStream());
		} catch (IOException e) {
			System.out.println("Problem on getting album art, could not open input stream of query-url");
			// myGUI.notification("Error", "Problem on getting Album Art, could not open input stream of query-url", "warning");
			return "img/icon.png";
		}

		try {
			outputStream = new BufferedOutputStream(new FileOutputStream(filename));
		} catch (FileNotFoundException e) {
			System.out.println("Problem on getting album art, could not initiate output stream of " + filename);
			// myGUI.notification("Error", "Problem on getting Album Art, could not initiate output stream of albumArt.html", "warning");
			return "img/icon.png";
		}

		dataPart = new byte[1024];
		try {
			while ((data = inputStream.read(dataPart)) != -1) {
				outputStream.write(dataPart, 0, data);
			}
		} catch (IOException e) {
			System.out.println("Problem on getting album art, could not write output stream of " + filename);
			// myGUI.notification("Error", "Problem on getting Album Art, could not write output stream of albumArt.html", "warning");
			return "img/icon.png";
		}
		try {
			outputStream.flush();
		} catch (IOException e) {
			System.out.println("Problem on getting album art, could not flush output stream of " + filename);
			// myGUI.notification("Error", "Problem on getting Album Art, could not flush output stream of albumArt.html", "warning");
		}
		try {
			outputStream.close();
		} catch (IOException e) {
			System.out.println("Problem on getting album art, could not close output stream of " + filename);
			// myGUI.notification("Error", "Problem on getting Album Art, could not close output stream of albumArt.html", "warning");
			return "img/icon.png";
		}
		try {
			inputStream.close();
		} catch (IOException e1) {
			System.out.println("Problem on getting album art, could not close input stream of " + filename);
			// myGUI.notification("Error", "Problem on getting Album Art, could not close input stream of albumArt.html", "warning");
			return "img/icon.png";
		}

		File xmlFile = new File(filename);
		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder dBuilder;
		org.w3c.dom.Document doc = null;

		try {
			dBuilder = dbFactory.newDocumentBuilder();
			doc = dBuilder.parse(xmlFile);
			doc.getDocumentElement().normalize();
		} catch (IOException | SAXException | ParserConfigurationException e) {
			System.out.println("Error parsing XML file " + filename + "\n");
			e.printStackTrace();
		}

		String status = doc.getDocumentElement().getAttribute("status");

		if (!status.equalsIgnoreCase("ok")) {
			System.out.println("No album art was found.");
			return "img/icon.png";
		}

		String coverURLString = null;
		NodeList nodeList = doc.getElementsByTagName("image");

		for (int i = 0; i < nodeList.getLength(); i++) {
			Node node = nodeList.item(i);
			if (node.getAttributes().getNamedItem("size").getNodeValue().equals(imageSize)) {
				coverURLString = node.getTextContent();
				break;
			}
		}

		URL coverURL;
		try {
			coverURL = new URL(coverURLString);
		} catch (MalformedURLException e) {
			System.out.println("Problem on getting album art, image url was not well-formed");
			// myGUI.notification("Error", "Problem on getting Album Art, image url was not well-formed", "warning");
			return "img/icon.png";
		}

		try {
			connnection = coverURL.openConnection();
			connnection.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; U; Linux i686; de; rv:1.9.2.3) Gecko/20100423 Ubuntu/10.04 (lucid) Firefox/3.6.3");

		} catch (IOException e) {
			System.out.println("Problem on getting album art, connection error");
			// myGUI.notification("Error", "Problem on getting Album Art", "warning");
			return "img/icon.png";
		}
		try {
			inputStream = new BufferedInputStream(connnection.getInputStream());
		} catch (IOException e) {
			System.out.println("Problem on getting album art, could not open input stream of image");
			// myGUI.notification("Error", "Problem on getting Album Art, could not open input stream of image", "warning");
			return "img/icon.png";
		}

		try {
			outputStream = new BufferedOutputStream(new FileOutputStream("albumArt/" + artist + " - " + album + ".jpg"));
		} catch (FileNotFoundException e) {
			System.out.println("Problem on getting album art, could not initiate output stream of " + "albumArt/" + artist + " - " + album + ".jpg");
			// myGUI.notification("Error", "Problem on getting Album Art, could not initiate output stream of " + "albumArt/" + artist + " - " + album + ".jpg",
			// "warning");
			return "img/icon.png";
		}

		dataPart = new byte[1024];
		try {
			while ((data = inputStream.read(dataPart)) != -1) {
				outputStream.write(dataPart, 0, data);
			}
		} catch (IOException e) {
			System.out.println("Problem on getting album art, could not write output stream of " + "albumArt/" + artist + " - " + album + ".jpg");
			// myGUI.notification("Error", "Problem on getting Album Art, could not write output stream of " + "albumArt/" + artist + " - " + album + ".jpg",
			// "warning");
			return "img/icon.png";
		}
		try {
			outputStream.flush();
		} catch (IOException e) {
			System.out.println("Problem on getting album art, could not flush output stream of " + "albumArt/" + artist + " - " + album + ".jpg");
			// myGUI.notification("Error", "Problem on getting Album Art, could not flush output stream of " + "albumArt/" + artist + " - " + album + ".jpg",
			// "warning");
			return "img/icon.png";
		}
		try {
			outputStream.close();
		} catch (IOException e) {
			System.out.println("Problem on getting album art, could not close output stream of " + "albumArt/" + artist + " - " + album + ".jpg");
			// myGUI.notification("Error", "Problem on getting Album Art, could not close output stream of " + "albumArt/" + artist + " - " + album + ".jpg",
			// "warning");
			return "img/icon.png";
		}
		try {
			inputStream.close();
		} catch (IOException e1) {
			System.out.println("Problem on getting album art, could not close input stream of " + "albumArt/" + artist + " - " + album + ".jpg");
			// myGUI.notification("Error", "Problem on getting Album Art, could not close input stream of " + "albumArt/" + artist + " - " + album + ".jpg",
			// "warning");
			return "img/icon.png";
		}

		rmtemp();

		file = new File("albumArt/" + artist + " - " + album + ".jpg");
		if (file.exists()) {
			return "albumArt/" + artist + " - " + album + ".jpg";
		}

		return "img/icon.png";
	}

	/*
	 * // download an album art and return file path public String
	 * getAlbumArtAltavista(String artist, String album) { if
	 * (artist.equalsIgnoreCase("youtube")) { return "img/yt.png"; }
	 * 
	 * File file = new File("albumArt/" + artist + " - " + album + ".jpg"); if
	 * (file.exists()) { return "albumArt/" + artist + " - " + album + ".jpg"; }
	 * 
	 * URLConnection connnection = null; InputStream inputStream = null;
	 * OutputStream outputStream = null; byte[] dataPart = new byte[1024]; int
	 * data; String filename = "albumArt.html";
	 * 
	 * artist = artist.replaceAll("[^A-Za-z0-9äöüÄÜÖ+-<> ]", "").replaceAll("/",
	 * ""); album = album.replaceAll("[^A-Za-z0-9äöüÄÜÖ+-<> ]",
	 * "").replaceAll("/", "");
	 * 
	 * URL queryurl = null; try { // queryurl = new
	 * URL(("http://images.google.com/images?q=" + artist + "+" +
	 * album).replace(" ", "+")); queryurl = new
	 * URL(("http://de.altavista.com/image/results?q=" + artist + "+" +
	 * album).replace(" ", "+")); } catch (MalformedURLException e) {
	 * System.out.
	 * println("Problem on getting Album Art, query-url was not well-formed");
	 * // myGUI.notification("Error",
	 * "Problem on getting Album Art, query-url was not well-formed",
	 * "warning"); return "img/icon.png"; }
	 * 
	 * try { connnection = queryurl.openConnection();
	 * connnection.setRequestProperty("User-Agent",
	 * "Mozilla/5.0 (X11; U; Linux i686; de; rv:1.9.2.3) Gecko/20100423 Ubuntu/10.04 (lucid) Firefox/3.6.3"
	 * );
	 * 
	 * } catch (IOException e) { System.out.println(
	 * "Problem on getting album art, can't connect to altavista image search");
	 * // myGUI.notification("Error",
	 * "Problem on getting Album Art, can't connect to images.google.com",
	 * "warning"); return "img/icon.png"; } try { inputStream = new
	 * BufferedInputStream(connnection.getInputStream()); } catch (IOException
	 * e) { System.out.println(
	 * "Problem on getting album art, could not open input stream of query-url"
	 * ); // myGUI.notification("Error",
	 * "Problem on getting Album Art, could not open input stream of query-url",
	 * "warning"); return "img/icon.png"; }
	 * 
	 * try { outputStream = new BufferedOutputStream(new
	 * FileOutputStream(filename)); } catch (FileNotFoundException e) {
	 * System.out.println(
	 * "Problem on getting album art, could not initiate output stream of albumArt.html"
	 * ); // myGUI.notification("Error",
	 * "Problem on getting Album Art, could not initiate output stream of albumArt.html"
	 * , "warning"); return "img/icon.png"; }
	 * 
	 * dataPart = new byte[1024]; try { while ((data =
	 * inputStream.read(dataPart)) != -1) { outputStream.write(dataPart, 0,
	 * data); } } catch (IOException e) { System.out.println(
	 * "Problem on getting album art, could not write output stream of albumArt.html"
	 * ); // myGUI.notification("Error",
	 * "Problem on getting Album Art, could not write output stream of albumArt.html"
	 * , "warning"); return "img/icon.png"; } try { outputStream.flush(); }
	 * catch (IOException e) { System.out.println(
	 * "Problem on getting album art, could not flush output stream of albumArt.html"
	 * ); // myGUI.notification("Error",
	 * "Problem on getting Album Art, could not flush output stream of albumArt.html"
	 * , "warning"); return "img/icon.png"; } try { outputStream.close(); }
	 * catch (IOException e) { System.out.println(
	 * "Problem on getting album art, could not close output stream of albumArt.html"
	 * ); // myGUI.notification("Error",
	 * "Problem on getting Album Art, could not close output stream of albumArt.html"
	 * , "warning"); return "img/icon.png"; } try { inputStream.close(); } catch
	 * (IOException e1) { System.out.println(
	 * "Problem on getting album art, could not close input stream of albumArt.html"
	 * ); // myGUI.notification("Error",
	 * "Problem on getting Album Art, could not close input stream of albumArt.html"
	 * , "warning"); return "img/icon.png"; }
	 * 
	 * BufferedReader br = null; try { br = new BufferedReader(new
	 * InputStreamReader(new FileInputStream(filename))); } catch
	 * (FileNotFoundException e) { System.out.println(
	 * "Problem on getting album art, could not open buffered reader of " +
	 * filename); // myGUI.notification("Error",
	 * "Problem on getting Album Art, could not open buffered reader of " +
	 * filename, "warning"); return "img/icon.png"; } StringBuffer contentOfFile
	 * = new StringBuffer(); String line; try { while ((line = br.readLine()) !=
	 * null) { contentOfFile.append(line); } } catch (IOException e) {
	 * System.out.println("Problem on getting album art, could not read " +
	 * filename); // myGUI.notification("Error",
	 * "Problem on getting Album Art, could not read " + filename, "warning");
	 * return "img/icon.png"; } try { br.close(); } catch (IOException e2) {
	 * System
	 * .out.println("Error while closing BufferedReader of file albumArt.html");
	 * } rmtemp(); String coverURLString = contentOfFile.toString(); try {
	 * coverURLString = coverURLString.substring(coverURLString.indexOf(
	 * "http://thm-a01.yimg.com/nimage/"),
	 * (coverURLString.indexOf("http://thm-a01.yimg.com/nimage/") + 47)); //
	 * coverURLString = coverURLString.substring(0,
	 * coverURLString.indexOf(":http")); } catch (Exception e) { if
	 * (albumArtFail == 0) { albumArtFail++; return getAlbumArt(artist, ""); }
	 * else { System.out.println(
	 * "Problem on getting album art, could not parse url from site"); //
	 * myGUI.notification("Error", "Problem on getting Album Art", "warning");
	 * return "img/icon.png"; } }
	 * 
	 * albumArtFail = 0; URL coverURL; try { coverURL = new URL(coverURLString);
	 * } catch (MalformedURLException e) { System.out.println(
	 * "Problem on getting album art, image url was not well-formed"); //
	 * myGUI.notification("Error",
	 * "Problem on getting Album Art, image url was not well-formed",
	 * "warning"); return "img/icon.png"; }
	 * 
	 * try { connnection = coverURL.openConnection();
	 * connnection.setRequestProperty("User-Agent",
	 * "Mozilla/5.0 (X11; U; Linux i686; de; rv:1.9.2.3) Gecko/20100423 Ubuntu/10.04 (lucid) Firefox/3.6.3"
	 * );
	 * 
	 * } catch (IOException e) {
	 * System.out.println("Problem on getting album art, connection error"); //
	 * myGUI.notification("Error", "Problem on getting Album Art", "warning");
	 * return "img/icon.png"; } try { inputStream = new
	 * BufferedInputStream(connnection.getInputStream()); } catch (IOException
	 * e) { System.out.println(
	 * "Problem on getting album art, could not open input stream of image"); //
	 * myGUI.notification("Error",
	 * "Problem on getting Album Art, could not open input stream of image",
	 * "warning"); return "img/icon.png"; }
	 * 
	 * try { outputStream = new BufferedOutputStream(new
	 * FileOutputStream("albumArt/" + artist + " - " + album + ".jpg")); } catch
	 * (FileNotFoundException e) { System.out.println(
	 * "Problem on getting album art, could not initiate output stream of " +
	 * "albumArt/" + artist + " - " + album + ".jpg"); //
	 * myGUI.notification("Error",
	 * "Problem on getting Album Art, could not initiate output stream of " +
	 * "albumArt/" + artist + " - " + album + ".jpg", // "warning"); return
	 * "img/icon.png"; }
	 * 
	 * dataPart = new byte[1024]; try { while ((data =
	 * inputStream.read(dataPart)) != -1) { outputStream.write(dataPart, 0,
	 * data); } } catch (IOException e) { System.out.println(
	 * "Problem on getting album art, could not write output stream of " +
	 * "albumArt/" + artist + " - " + album + ".jpg"); //
	 * myGUI.notification("Error",
	 * "Problem on getting Album Art, could not write output stream of " +
	 * "albumArt/" + artist + " - " + album + ".jpg", // "warning"); return
	 * "img/icon.png"; } try { outputStream.flush(); } catch (IOException e) {
	 * System.out.println(
	 * "Problem on getting album art, could not flush output stream of " +
	 * "albumArt/" + artist + " - " + album + ".jpg"); //
	 * myGUI.notification("Error",
	 * "Problem on getting Album Art, could not flush output stream of " +
	 * "albumArt/" + artist + " - " + album + ".jpg", // "warning"); return
	 * "img/icon.png"; } try { outputStream.close(); } catch (IOException e) {
	 * System.out.println(
	 * "Problem on getting album art, could not close output stream of " +
	 * "albumArt/" + artist + " - " + album + ".jpg"); //
	 * myGUI.notification("Error",
	 * "Problem on getting Album Art, could not close output stream of " +
	 * "albumArt/" + artist + " - " + album + ".jpg", // "warning"); return
	 * "img/icon.png"; } try { inputStream.close(); } catch (IOException e1) {
	 * System
	 * .out.println("Problem on getting album art, could not close input stream of "
	 * + "albumArt/" + artist + " - " + album + ".jpg"); //
	 * myGUI.notification("Error",
	 * "Problem on getting Album Art, could not close input stream of " +
	 * "albumArt/" + artist + " - " + album + ".jpg", // "warning"); return
	 * "img/icon.png"; }
	 * 
	 * rmtemp();
	 * 
	 * file = new File("albumArt/" + artist + " - " + album + ".jpg"); if
	 * (file.exists()) { return "albumArt/" + artist + " - " + album + ".jpg"; }
	 * else { return "img/icon.png"; }
	 * 
	 * }
	 */

	private void rmtemp() {
		File file = new File("albumArt.xml");
		if (file.exists()) {
			file.delete();
		}
	}

	/*
	 * @SuppressWarnings("unchecked") public String getAlbumArtFreecovers(String
	 * artist, String album) { if (artist.equalsIgnoreCase("youtube")) return
	 * "img/yt.png";
	 * 
	 * try { artist = artist.replaceAll("[^A-Za-z0-9+-<> ]", "").replaceAll("/",
	 * ""); album = album.replaceAll("[^A-Za-z0-9+-<> ]", "").replaceAll("/",
	 * ""); InputStream inputStream; OutputStream outputStream; byte[] dataPart;
	 * int data;
	 * 
	 * File file = new File("albumArt/" + artist + "-" + album + ".jpg"); if
	 * (file.exists()) { return "albumArt/" + artist + "-" + album + ".jpg"; }
	 * 
	 * URL freecoversURL = new URL(("http://www.freecovers.net/api/search/" +
	 * artist + "+" + album + "/Music CD").replace(" ", "+")); URLConnection
	 * connnection = freecoversURL.openConnection();
	 * 
	 * // System.out.println(freecoversURL);
	 * 
	 * BufferedReader in = new BufferedReader(new
	 * InputStreamReader(freecoversURL.openStream(), "UTF-8"));
	 * 
	 * Writer out = new BufferedWriter(new OutputStreamWriter(new
	 * FileOutputStream("covers.xml"), "UTF8"));
	 * 
	 * String thisLine;
	 * 
	 * while ((thisLine = in.readLine()) != null) { thisLine =
	 * thisLine.replaceAll("[^A-Za-z0-9+-<>üäöÄÖÜß\"?= ]", "");
	 * out.write(thisLine + "\n"); }
	 * 
	 * out.flush(); out.close(); in.close();
	 * 
	 * SAXBuilder sxbuild = new SAXBuilder(); InputSource inputSource = new
	 * InputSource("covers.xml"); Document document =
	 * sxbuild.build(inputSource); Element root = document.getRootElement();
	 * 
	 * new File("covers.xml").delete();
	 * 
	 * if (root.getAttributeValue("stat").equals("ok")) {
	 * 
	 * List<Element> titleList = root.getChildren("title"); List<Element>
	 * coverList;
	 * 
	 * for (Element titelElement : titleList) { coverList =
	 * titelElement.getChild("covers").getChildren("cover"); for (Element
	 * coverElement : coverList) { if
	 * (coverElement.getChild("type").getText().equals("front")) { freecoversURL
	 * = new URL(coverElement.getChild("preview").getText());
	 * 
	 * connnection = freecoversURL.openConnection(); inputStream = new
	 * BufferedInputStream(connnection.getInputStream()); outputStream = new
	 * BufferedOutputStream(new FileOutputStream("albumArt/" + artist + "-" +
	 * album + ".jpg")); dataPart = new byte[1024]; while ((data =
	 * inputStream.read(dataPart)) != -1) { outputStream.write(dataPart, 0,
	 * data); } outputStream.flush(); outputStream.close(); inputStream.close();
	 * 
	 * return "albumArt/" + artist + "-" + album + ".jpg"; } } } }
	 * 
	 * } catch (Exception e) { return "img/icon.png"; }
	 * 
	 * return "img/icon.png"; }
	 */
	/*
	 * @SuppressWarnings("unchecked") public ArrayList<MPDSong>
	 * youtubeSearchDisabled(String q) { URLConnection connnection; InputStream
	 * inputStream; OutputStream outputStream; byte[] dataPart; int data;
	 * Document document = null; Element root; URL url = null; BufferedReader br
	 * = null;
	 * 
	 * // List which will contain Stream-URLs ArrayList<MPDSong> youtubeResults
	 * = new ArrayList<MPDSong>(); q = q.replace(" ", "+").replace("ä",
	 * "a").replace("ö", "o").replace("ü", "u");
	 * 
	 * if (q.isEmpty()) return youtubeResults;
	 * 
	 * URL youtubeURL; try { youtubeURL = new
	 * URL("http://gdata.youtube.com/feeds/api/videos?q=" + q); connnection =
	 * youtubeURL.openConnection(); inputStream = new
	 * BufferedInputStream(connnection.getInputStream()); outputStream = new
	 * BufferedOutputStream(new FileOutputStream("youtube.xml")); dataPart = new
	 * byte[1024]; while ((data = inputStream.read(dataPart)) != -1) {
	 * outputStream.write(dataPart, 0, data); } outputStream.flush();
	 * outputStream.close(); inputStream.close(); } catch (MalformedURLException
	 * e) { System.out.println(
	 * "MalformedURLException while trying to search songs on youtube."); return
	 * new ArrayList<MPDSong>(); } catch (IOException e) {
	 * System.out.println("IOException while trying to search songs on youtube."
	 * ); return new ArrayList<MPDSong>(); }
	 * 
	 * SAXBuilder sxbuild = new SAXBuilder(); InputSource inputSource = new
	 * InputSource("youtube.xml"); try { document = sxbuild.build(inputSource);
	 * } catch (JDOMException e) {
	 * System.out.println("JDOMException while trying to search songs on youtube."
	 * ); return new ArrayList<MPDSong>(); } catch (IOException e) {
	 * System.out.println
	 * ("IOException while trying to search songs on youtube."); return new
	 * ArrayList<MPDSong>(); } root = document.getRootElement();
	 * 
	 * Namespace openSearch = root.getNamespace("openSearch"); List<Element>
	 * resultList = root.getChildren();
	 * 
	 * Namespace media = root.getChild("totalResults",
	 * openSearch).getNamespace("media");
	 * 
	 * for (Element resultElement : resultList) { if
	 * (resultElement.getName().equals("entry")) {
	 * 
	 * String title = null;
	 * 
	 * List<Element> liste = resultElement.getChildren();
	 * 
	 * for (Element elemant : liste) { if (elemant.getName().equals("title")) {
	 * title = elemant.getText(); } }
	 * 
	 * liste = null;
	 * 
	 * liste = resultElement.getChild("group", media).getChildren();
	 * 
	 * if (liste.size() > 5) {
	 * 
	 * try { url = new URL(resultElement.getChild("group",
	 * media).getChild("player", media).getAttributeValue("url")); //
	 * System.out.println(url.toString()+"\n\n\n"); } catch
	 * (MalformedURLException e) { System.out.println(
	 * "MalformedURLException while trying to search songs on youtube."); return
	 * new ArrayList<MPDSong>(); } String filename = url.getFile(); //
	 * filename.replaceAll("watch", "s"); //
	 * filename.replaceAll("&feature=youtube_gdata", "s");
	 * 
	 * filename = filename.substring(9, 20); //
	 * System.out.println(filename+"\n\n\n");
	 * 
	 * // http://www.youtube.com/get_video_info?video_id=
	 * 
	 * try { url = new URL("http://www.youtube.com/get_video_info?video_id=" +
	 * filename); } catch (MalformedURLException e1) { System.out.println(
	 * "MalformedURLException while trying to search songs on youtube."); return
	 * new ArrayList<MPDSong>(); }
	 * 
	 * try { connnection = url.openConnection();
	 * 
	 * inputStream = new BufferedInputStream(connnection.getInputStream());
	 * outputStream = new BufferedOutputStream(new FileOutputStream(filename));
	 * dataPart = new byte[1024]; while ((data = inputStream.read(dataPart)) !=
	 * -1) { outputStream.write(dataPart, 0, data); } outputStream.flush();
	 * outputStream.close(); inputStream.close();
	 * 
	 * } catch (IOException e) {
	 * System.out.println("IOException while trying to search songs on youtube."
	 * ); return new ArrayList<MPDSong>(); }
	 * 
	 * try { br = new BufferedReader(new InputStreamReader(new
	 * FileInputStream(filename))); } catch (FileNotFoundException e) {
	 * System.out
	 * .println("FileNotFoundException while trying to search songs on youtube."
	 * ); return new ArrayList<MPDSong>(); } StringBuffer contentOfFile = new
	 * StringBuffer(); String line; try { while ((line = br.readLine()) != null)
	 * { contentOfFile.append(line); } } catch (IOException e) {
	 * System.out.println
	 * ("IOException while trying to search songs on youtube."); return new
	 * ArrayList<MPDSong>(); } String streamURL = contentOfFile.toString(); //
	 * System.out.println(streamURL); try { streamURL =
	 * streamURL.substring(streamURL.indexOf("&token=") + "&token=".length(),
	 * streamURL.indexOf("&thumbnail_url=")); // hier lauert // der // gemeine
	 * // fehler System.out.println(streamURL); streamURL =
	 * "http://youtube.com/get_video?video_id=" + filename + "&t=" + streamURL;
	 * System.out.println(streamURL); } catch (Exception e) {
	 * System.out.println(
	 * "Dieses Video ist in deinem Land verboten Exception *kotzimkreis*");
	 * System.out.println(streamURL); // e.printStackTrace(); continue; } //
	 * streamURL = streamURL.replace("generate_204", // "videoplayback");
	 * 
	 * MPDSong youtubeStream = new MPDSong();
	 * 
	 * youtubeStream.setFile(streamURL); youtubeStream.setArtist(new
	 * MPDArtist("Youtube")); youtubeStream.setAlbum(new MPDAlbum("Youtube"));
	 * youtubeStream.setTitle(title);
	 * 
	 * youtubeResults.add(youtubeStream);
	 * 
	 * File file = new File(filename);
	 * 
	 * if (file.exists()) { file.delete(); }
	 * 
	 * }
	 * 
	 * } }
	 * 
	 * for (MPDSong s : youtubeResults) getSongList().add(s);
	 * 
	 * new File("youtube.xml").delete();
	 * 
	 * return youtubeResults; }
	 */

	public boolean checkPassword(String pass) {
		if (properties.getProperty("adminPass").equals(pass))
			return true;
		else
			return false;
	}

	public ArrayList<MPDSong> youtubeSearch(String q) {
		return youtubeSearch(q, 0);
	}

	public ArrayList<MPDSong> youtubeSearch(String q, int start) {
		URLConnection connnection;
		InputStream inputStream;
		OutputStream outputStream;
		byte[] dataPart;
		int data;
		Document document = null;
		Element root;
		List<Element> resultList;
		String queryString = q;

		// List which will contain Stream-URLs
		ArrayList<MPDSong> fourSharedResults = new ArrayList<MPDSong>();

		// Translates query string into x-www-form-urlencoded format
		try {
			queryString = URLEncoder.encode(queryString, "UTF-8");
		} catch (UnsupportedEncodingException e1) {
			queryString = queryString.replace(" ", "+").replace("ä", "%C3%A4").replace("ö", "%C3%B6").replace("ü", "%C3%BC").replace("Ä", "%C3%A4").replace("Ö", "%C3%B6").replace("Ü", "%C3%BC").replace("ß", "%C3%9F");
		}

		if (queryString.isEmpty())
			return fourSharedResults;
		String queryURLString = "http://search.4shared.com/network/searchXml.jsp?q=" + queryString + "&searchCategory=music/audio&searchExtention=mp3&sortType=1&searchmode=3";
		URL fourSharedURL;
		try {

			fourSharedURL = new URL(queryURLString);
			connnection = fourSharedURL.openConnection();
			inputStream = new BufferedInputStream(connnection.getInputStream());
			outputStream = new BufferedOutputStream(new FileOutputStream("fourShared.xml"));
			dataPart = new byte[1024];
			while ((data = inputStream.read(dataPart)) != -1) {
				outputStream.write(dataPart, 0, data);
			}
			outputStream.flush();
			outputStream.close();
			inputStream.close();
		} catch (MalformedURLException e) {
			System.out.println("MalformedURLException while trying to search songs on youtube.");
			return new ArrayList<MPDSong>();
		} catch (IOException e) {
			System.out.println("IOException while trying to search songs on youtube. (outputStream)");
			return new ArrayList<MPDSong>();
		}

		SAXBuilder sxbuild = new SAXBuilder();
		InputSource inputSource = new InputSource("fourShared.xml");
		try {
			document = sxbuild.build(inputSource);
		} catch (JDOMException e) {
			System.out.println("JDOMException while trying to search songs on youtube.");
			return new ArrayList<MPDSong>();
		} catch (IOException e) {
			System.out.println("IOException while trying to search songs on youtube. (InputSource)");
			return new ArrayList<MPDSong>();
		}
		root = document.getRootElement();

		try {
			resultList = root.getChild("result-files").getChildren();
		} catch (NullPointerException e) {
			return fourSharedResults;
		}

		for (Element resultElement : resultList) {
			if (resultElement.getName().equals("file")) {
				String title = null;
				title = resultElement.getChild("name").getText();
				title = title.replaceAll(".mp3", "").replaceAll(".MP3", "").replaceAll(".Mp3", "").replaceAll("_", " ");
				String streamURL = resultElement.getChild("flash-preview-url").getText();
				MPDSong fourSharedStream = new MPDSong();

				fourSharedStream.setFile(streamURL);
				fourSharedStream.setArtist(new MPDArtist("Youtube"));
				fourSharedStream.setAlbum(new MPDAlbum("Youtube"));
				fourSharedStream.setTitle(title);

				fourSharedResults.add(fourSharedStream);
			}
		}

		/*
		 * for (MPDSong s : fourSharedResults) getSongList().add(s);
		 */

		new File("fourShared.xml").delete();

		// next 9 results
		if (start == 0)
			fourSharedResults.addAll(youtubeSearch(q, 10));

		return fourSharedResults;
	}

}